package utils

import (
	"errors"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/cache"
)

var cc cache.Cache

func InitCache() {
	logPrefix := "[InitCache]"

	cc = nil
	config := beego.AppConfig.String("cache")
	if config == "memory" {
		initMemoryCache()
	}
	beego.Info(logPrefix, "init cache, config:", config)
}

func initMemoryCache() {
	logPrefix := "[initMemoryCache]"
	var err error
	//
	cc, err = cache.NewCache("memory", `{"interval":60}`)
	if err != nil {
		beego.Critical(logPrefix, "init memory cache fail, err:", err.Error())
	}
}

func GetCache(key string) interface{} {
	if cc == nil {
		return nil
	}
	return cc.Get(key)
}

func PutCache(key string, value interface{}, timeout int) error {
	if cc == nil {
		return errors.New("cache not exist")
	}
	return cc.Put(key, value, time.Duration(timeout)*time.Second)
}

func DelCache(key string) error {
	if cc == nil {
		return errors.New("cache not exist")
	}
	return cc.Delete(key)
}

func IsExistCache(key string) bool {
	if cc == nil {
		return false
	}
	return cc.IsExist(key)
}

func IncrCache(key string) error {
	if cc == nil {
		return errors.New("cache not exist")
	}
	return cc.Incr(key)
}

func DecrCache(key string) error {
	if cc == nil {
		return errors.New("cache not exist")
	}
	return cc.Decr(key)
}
